package com.nord.PhoneBook;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.nord.R;
import com.nord.Menus.Menus;
import com.nord.Services.SQLiteAdapter;
import com.nord.WebTools.HtmlBrowser;

import android.net.Uri;
import android.os.AsyncTask;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Typeface;
import android.support.v4.widget.SimpleCursorAdapter;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;

import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AlphabetIndexer;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SectionIndexer;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class PhoneBook extends Activity {

	ListView listView;
	SimpleCursorAdapter mAdapter;
	boolean RESTART = false;

	@Override
	public void onResume() {
		super.onResume();
		setContentView(R.layout.activity_phone_book);
		listView = (ListView) findViewById(R.id.listView);
		listView.setFastScrollEnabled(true);
		listView.setScrollingCacheEnabled(true);

		Button menuBanner = (Button) findViewById(R.id.menuBanner);
		Typeface tf = Typeface.createFromAsset(getAssets(),"DaysOne-Regular.ttf");
		menuBanner.setTypeface(tf);

		new userInformationExtractor().execute(true);

		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, final int position, long arg3) {
				final Cursor cursor = (Cursor) listView.getItemAtPosition(position);
				
				if (!cursor.getString(cursor.getColumnIndex("phonenumber")).contains("Ekkert") &&
						!cursor.getString(cursor.getColumnIndex("phonenumber")).matches("")){
					
					final AlertDialog dialog = new AlertDialog.Builder(
							PhoneBook.this).create();
					dialog.setTitle("Hringja í:\n"
							+ cursor.getString(cursor.getColumnIndex("phonenumber")));
					dialog.setMessage("Ertu viss að þú vilt hringja í númerið "
							+ cursor.getString(cursor.getColumnIndex("phonenumber")) + " ?");

					dialog.setButton2("Nyet",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.dismiss();
								}
							});

					dialog.setButton("Já",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									String url = "tel:"
											+ cursor.getString(cursor.getColumnIndex("phonenumber"));
									Intent intent = new Intent(
											Intent.ACTION_CALL, Uri.parse(url));
									startActivity(intent);

									EndCallListener callListener = new EndCallListener();
									TelephonyManager mTM = (TelephonyManager) PhoneBook.this
											.getSystemService(Context.TELEPHONY_SERVICE);
									mTM.listen(
											callListener,
											PhoneStateListener.LISTEN_CALL_STATE);
									if (RESTART) {
										RESTART = false;
										finish();
										startActivity(new Intent(
												PhoneBook.this, PhoneBook.class));
									}

								}
							});

					dialog.show();
				}
			}
		});
	}

	private class EndCallListener extends PhoneStateListener {
		@Override
		public void onCallStateChanged(int state, String incomingNumber) {
			if (TelephonyManager.CALL_STATE_IDLE == state) {
				RESTART = true;
			}
		}
	}

	private class userInformationExtractor extends AsyncTask<Boolean, Integer, Cursor> {
		ProgressDialog progressBar;
		SQLiteAdapter sql;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressBar = new ProgressDialog(PhoneBook.this);
			progressBar.setCancelable(false);
			progressBar
					.setMessage("Er að sækja símanúmer frá\nwww.nord.is/ ...");
			progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressBar.setProgress(0);
			progressBar.setMax(100);
			progressBar.show();

		}

		@Override
		protected Cursor doInBackground(Boolean... params) {
			String data[] = HtmlBrowser.getExecutor("http://www.nord.is/api/nord/users/?format=json&limit=0");
			sql = new SQLiteAdapter(PhoneBook.this);
			if(!data[0].contains("Exception")){
				sql.open("W");
				sql.deleteAll("phonebook");
				Cursor cursor = HtmlBrowser.jsonPhoneBookProcessor(sql,data[0]);
				return cursor;
			
			} else {
				sql.open("R");
				Cursor cursor = sql.queryPhoneBook();
				if(cursor.getCount() != 0){
					return cursor;
				}
				else
					return null;
			}
		}

		@Override
		protected void onPostExecute(Cursor cursor) {
			progressBar.dismiss();
			if(cursor != null){
				String[] from = { "fullname", "phonenumber", "email" };
				int[] to = { R.id.fullname, R.id.phonenumber, R.id.email };
				listView.setAdapter(new PhoneBookAlphabetAdapter(
						PhoneBook.this, R.layout.list_phone_book, cursor, from, to));
				sql.close();
				
			} else{
				String message = "Til að skoða númer í fyrsta sinn þarf net-tengingu";
				Intent menus = new Intent(PhoneBook.this, Menus.class);
				menus.putExtra("USERNAME", getIntent().getExtras()
						.getString("USERNAME"));
				Toast toast = Toast.makeText(PhoneBook.this, message,
						Toast.LENGTH_LONG);
				toast.show();
				startActivity(menus);
			}
		}
	}

	public class PhoneBookAlphabetAdapter extends SimpleCursorAdapter implements
			SectionIndexer {
		AlphabetIndexer alphaIndexer;

		@SuppressWarnings("deprecation")
		public PhoneBookAlphabetAdapter(Context context, int layout, Cursor c,
				String[] from, int[] to) {
			super(context, layout, c, from, to);
			alphaIndexer = new AlphabetIndexer(c,
					c.getColumnIndexOrThrow("fullname"),
					" AÁBDEFGHIÍKLMNOÓPRSTUÚVWYÞ");

		}

		@Override
		public int getPositionForSection(int section) {
			return alphaIndexer.getPositionForSection(section); // use the
																// indexer
		}

		@Override
		public int getSectionForPosition(int position) {
			return alphaIndexer.getSectionForPosition(position); // use the
																	// indexer
		}

		@Override
		public Object[] getSections() {
			return alphaIndexer.getSections(); // use the indexer
		}
	}
}
